<template>
  <div class="container">
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-row>
          <el-col :span="6">
            <el-form-item label="用户名">
              <el-input
                v-model="searchForm.username"
                placeholder="请输入用户名"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="6">
            <el-form-item label="昵称">
              <el-input
                v-model="searchForm.nickname"
                placeholder="请输入昵称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别">
              <el-select v-model="searchForm.sex" placeholder="请选择性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleResetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="common-layout-main">
      <div class="common-head">
        <el-button type="primary" @click="handleAdd">添加用户</el-button>
      </div>
      <el-table :data="users" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="nickname"
          label="昵称"
          width="120"
        ></el-table-column>
        <el-table-column prop="age" label="年龄" width="80"></el-table-column>
        <el-table-column prop="sex" label="性别" width="80"></el-table-column>
        <el-table-column
          prop="gmtCreate"
          label="创建时间"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="gmtModified"
          label="修改时间"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:currentPage="pagination.pageNum"
        v-model="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 50, 100, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchUsers"
        @current-change="fetchUsers"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="formRef" :model="user" :rules="rules">
        <el-form-item
          label="用户名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="user.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
          v-if="!user.id"
        >
          <el-input
            v-model="user.password"
            autocomplete="off"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="昵称"
          :label-width="formLabelWidth"
          prop="nickname"
        >
          <el-input v-model="user.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
          <el-input
            v-model="user.age"
            type="number"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
          <el-select v-model="user.sex">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  getUserList,
  getUserInfoByid,
  deleteUser,
  addUser,
  updateUser,
} from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { FormInstance } from "element-plus";
export default {
  setup() {
    const users = ref([]);
    const user = reactive({
      id: "",
      username: "",
      password: "",
      nickname: "",
      age: "",
      sex: "",
    });
    const searchForm = reactive({
      username: null,
      nickname: null,
      sex: null,
    });
    const pagination = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 0,
    });
    const dialogVisible = ref(false);
    const dialogTitle = ref("");
    const formLabelWidth = "120px";

    const rules = reactive({
      username: [
        { required: true, message: "用户名不能为空", trigger: "blur" },
      ],
      password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
      nickname: [{ required: true, message: "昵称不能为空", trigger: "blur" }],
      age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
      sex: [{ required: true, message: "性别不能为空", trigger: "change" }],
    });

    const formRef = ref<FormInstance | null>(null);

    const fetchUsers = async () => {
      try {
        const response = await getUserList({
          ...searchForm,
          ...pagination,
        });
        users.value = response.data;
        pagination.total = response.total;
      } catch (error) {
        console.error("Error fetching users:", error);
      }
    };

    const handleAdd = () => {
      Object.assign(user, {
        id: "",
        username: "",
        password: "",
        nickname: "",
        age: "",
        sex: "",
      });
      dialogTitle.value = "添加用户";
      dialogVisible.value = true;
    };

    const handleEdit = async (id: Number) => {
      const { data } = await getUserInfoByid(id);
      Object.assign(user, data);
      dialogTitle.value = "编辑用户";
      dialogVisible.value = true;
    };

    const handleDelete = async (id) => {
      try {
        ElMessageBox.confirm("是否删除次数据？", "Warning", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          await deleteUser(id);
          fetchUsers();
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        });
      } catch (error) {
        console.error("Error deleting user:", error);
      }
    };

    const handleSubmit = async () => {
      formRef.value.validate(async (valid: boolean) => {
        if (valid) {
          if (user.id) {
            try {
              await updateUser(user);
              fetchUsers();
              ElMessage({
                type: "success",
                message: "修改成功",
              });
            } catch (error) {
              console.error("Error creating user:", error);
            }
          } else {
            try {
              await addUser(user);
              fetchUsers();
              ElMessage({
                type: "success",
                message: "添加成功",
              });
            } catch (error) {
              console.error("Error updating user:", error);
            }
          }
          dialogVisible.value = false;
        } else {
          console.log("Form validation failed.");
        }
      });
    };

    const handleSearch = () => {
      pagination.pageNum = 1;
      fetchUsers();
    };

    const handleResetSearch = () => {
      Object.assign(searchForm, { username: null, nickname: null, sex: null });
      handleSearch();
    };
    onMounted(() => {
      fetchUsers();
    });

    return {
      users,
      user,
      searchForm,
      dialogVisible,
      dialogTitle,
      pagination,
      formLabelWidth,
      rules,
      formRef,
      fetchUsers,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit,
      handleSearch,
      handleResetSearch,
    };
  },
};
</script>

<style lang="scss" scoped>
.container {
  flex: 1;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .search-form {
    background: #fff;
    flex-shrink: 0;
    margin-bottom: 10px;
    padding: 15px 10px 0;
    position: relative;
    .el-col {
      padding: 0 6px;
    }

    .el-form-item {
      width: 100%;
      display: flex;
      margin-bottom: 14px !important;

      .el-form-item__label {
        flex-shrink: 0;
        padding-right: 12px;
      }

      .el-form-item__content {
        flex: 1;
      }

      .el-input,
      .el-select,
      .el-cascader,
      .comSelect-container,
      .el-date-editor {
        width: 100%;
      }
    }
  }
  .common-layout-main {
    flex: 1;
    padding: 15px 10px 0;
    background-color: #fff;
    height: 100%;
    overflow: hidden;
  }
}
</style>
